package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.ILoginService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author karlfu
 * @since 2022/06/18 14:49
 */

@Service
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserConverterMapper userConverterMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;


    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        UserLoginResponse userLoginResponse = new UserLoginResponse();

        // 验证用户名
        userLoginRequest.requestCheck();
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userLoginRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(memberList)) {
            userLoginResponse.setCode(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.REQUEST_DATA_ERROR.getMessage());
            return userLoginResponse;
        }

        Member member = memberList.get(0);

        // 判断用户是否激活
        String isVerified = member.getIsVerified();
        if (isVerified.equals("N")) {
            userLoginResponse.setCode(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.REQUEST_DATA_ERROR.getMessage());
            return userLoginResponse;
        }

        // 验证密码
        String password = userLoginRequest.getPassword();
        String encodedUserPwd = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        if (!encodedUserPwd.equals(member.getPassword())) {
            userLoginResponse.setCode(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.REQUEST_DATA_ERROR.getMessage());
            return userLoginResponse;
        }

        // 通过账号密码校验 则产生JWT token
        Map<String, Object> map = new HashMap<>();
        map.put("uid", member.getId());
        map.put("file", member.getFile());
        map.put("username", member.getUsername());

        String jwtToken = JwtTokenUtils.builder().msg(JSON.toJSONString(map)).build().creatJwtToken();

        userLoginResponse = userConverterMapper.converter(member);
        userLoginResponse.setToken(jwtToken);
        userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return userLoginResponse;
    }

    @Override
    public String verify(String verifyUsername) {
        return userVerifyMapper.queryUidByUsername(verifyUsername);
    }

    @Override
    @Transactional
    // 两个表的更新操作要封装为事务
    public UserVerifyResponse verified(String verifyUsername) {
        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();
        int updateUserVerify = userVerifyMapper.updateVerify(verifyUsername,"Y");
        int updateMemberVerify = memberMapper.updateVerify(verifyUsername,"Y");
        try {
            Boolean updateVerifyOk = (updateUserVerify == 1 && updateMemberVerify == 1);
            if (!updateVerifyOk) {
                throw new Exception();
            }
        } catch (Exception e) {
            e.printStackTrace();
            userVerifyResponse.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            userVerifyResponse.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
            return userVerifyResponse;
        }
        userVerifyResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userVerifyResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return userVerifyResponse;
    }

    @Override
    public String loginVerify(String uid) {
        return memberMapper.queryUsernameByUid(uid);
    }
}
